package com.x.service.transactional;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.x.dao.LogDAO;
import com.x.dao.PaddingDAO;
import com.x.dao.SubmitDAO;
import com.x.model.Log;
import com.x.model.Padding;
import com.x.model.Submit;

@Component("paddingService")
public class PaddingService {

	@Autowired
	private PaddingDAO paddingDAO;
	@Autowired
	private LogDAO logDAO;
	@Autowired
	private SubmitDAO submitDAO;

	public Map<String, Object> list(int startIndex, int length,
			List<String[]> wherePart, List<String[]> odrerPart) {
		return paddingDAO.list(startIndex, length, wherePart, odrerPart);
	}

	public Map<String, Object> listReady(int startIndex, int length,
			List<String[]> wherePart, List<String[]> odrerPart) {
		return paddingDAO.listReady(startIndex, length, wherePart, odrerPart);
	}

	public Map<String, Object> listExsit(int startIndex, int length,
			List<String[]> wherePart, List<String[]> odrerPart) {
		return paddingDAO.listExsit(startIndex, length, wherePart, odrerPart);
	}

	public Map<String, Object> find(String id) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> result = new HashMap<>();
		Padding padding = paddingDAO.find(id);
		result.put("id", padding.getId());
		result.put("fc", padding.getFc());
		result.put("sm", padding.getShipMethod());
		result.put("padding", padding.getPadding());
		result.put("province", padding.getProvince());
		result.put("city", padding.getCity());
		result.put("district", padding.getDistrict());
		result.put("padding", padding.getPadding());
		String startDate = format.format(padding.getStartDate());
		String endDate = format.format(padding.getEndDate());
		result.put("startDate", startDate);
		result.put("endDate", endDate);
		return result;
	}

	public void delete(String id) {
		paddingDAO.delete(id);
		logDAO.deleteByPaddingID(id);
	}

	public boolean noConflict(String fc, String sm, String province,
			String city, String district, Date start, Date end) {
		return paddingDAO.noConflict(fc, sm, province, city, district, start,
				end);
	}

	public void create(String fc, String sm, int paddingHour, String province,
			String city, String district, Date start, Date end) {
		Padding padding = new Padding();
		padding.setFc(fc);
		padding.setShipMethod(sm);
		padding.setPadding(paddingHour);
		padding.setProvince(province);
		padding.setCity(city);
		padding.setDistrict(district);
		padding.setStartDate(start);
		padding.setEndDate(end);
		paddingDAO.save(padding);
		String paddingID = padding.getId();
		int priority = 0;
		if (!district.equals("ALL")) {
			priority = 3;
		} else if (!city.equals("ALL")) {
			priority = 2;
		} else if (!province.equals("ALL")) {
			priority = 1;
		}
		Calendar timeCounter = Calendar.getInstance();
		timeCounter.setTime(start);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end);
		while (!timeCounter.after(endTime)) {
			Log log = new Log();
			log.setPaddingDate(timeCounter.getTime());
			log.setPaddingID(paddingID);
			log.setPriority(priority);
			timeCounter.add(Calendar.DATE, 1);
			logDAO.save(log);
		}
	}

	public void update(String id, String fc, String sm, String province,
			String city, String district, String startDate, String endDate) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Padding padding = paddingDAO.load(id);
		try {
			padding.setId(id);
			padding.setFc(fc);
			padding.setShipMethod(sm);
			padding.setProvince(province);
			padding.setCity(city);
			padding.setDistrict(district);
			Date start = format.parse(startDate);
			Date end = format.parse(endDate);
			padding.setStartDate(start);
			padding.setEndDate(end);
			paddingDAO.save(padding);
			logDAO.deleteByPaddingID(padding.getId());
			String paddingID = padding.getId();
			int priority = 0;
			if (!district.equals("ALL")) {
				priority = 3;
			} else if (!city.equals("ALL")) {
				priority = 2;
			} else if (!province.equals("ALL")) {
				priority = 1;
			}
			Calendar timeCounter = Calendar.getInstance();
			timeCounter.setTime(start);
			Calendar endTime = Calendar.getInstance();
			endTime.setTime(end);
			while (!timeCounter.after(endTime)) {
				Log log = new Log();
				log.setPaddingDate(timeCounter.getTime());
				log.setPaddingID(paddingID);
				log.setPriority(priority);
				timeCounter.add(Calendar.DATE, 1);
				logDAO.save(log);
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

	public List<String> getFCSuggestion(String fc) {
		return paddingDAO.getFCSuggestion(fc);
	}

	public List<String> getSMSuggestion(String sm) {
		return paddingDAO.getSMSuggestion(sm);
	}

	public List<String> getPaddingSuggestion(String padding) {
		return paddingDAO.getPaddingSuggestion(padding);
	}

	public List<String> getProvinceSuggestion(String province) {
		return paddingDAO.getProvinceSuggestion(province);
	}

	public List<String> getCitySuggestion(String city) {
		return paddingDAO.getCitySuggestion(city);
	}

	public List<String> getDistrictSuggestion(String district) {
		return paddingDAO.getDistrictSuggestion(district);
	}

	public void submit(String tt, String reason, String userId) {
		Submit submit = new Submit();
		submit.setReason(reason);
		submit.setTt(tt);
		submit.setCreatetime(new Date());
		submit.setUserId(userId);
		submitDAO.save(submit);
		List<Padding> newPaddingList = paddingDAO.listByProperties("status", 0);
		for (Padding padding : newPaddingList) {
			padding.setSubmit(submit);
			padding.setStatus(1);
			paddingDAO.save(padding);
		}

	}

	public void deploy(HttpServletResponse response) {
		try {
			List<Padding> readyList = paddingDAO.listReady();
			SXSSFWorkbook wb = new SXSSFWorkbook(100);
			Sheet sh = wb.createSheet();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			for (int rownum = 0; rownum < readyList.size(); rownum++) {
				Row row = sh.createRow(rownum);
				Padding padding = readyList.get(rownum);
				Cell cell = row.createCell(0);
				cell.setCellValue(padding.getFc());
				cell = row.createCell(1);
				cell.setCellValue(padding.getShipMethod());
				cell = row.createCell(2);
				cell.setCellValue(padding.getProvince());
				cell = row.createCell(3);
				cell.setCellValue(padding.getCity());
				cell = row.createCell(4);
				cell.setCellValue(padding.getDistrict());
				cell = row.createCell(5);
				cell.setCellValue(format.format(padding.getStartDate()));
				cell = row.createCell(6);
				cell.setCellValue(format.format(padding.getEndDate()));
				padding.setStatus(2);
				paddingDAO.save(padding);
			}
			String fileName = "deployFile.xlsx";
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream outputStream = new BufferedOutputStream(
					response.getOutputStream());
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
			wb.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
